import { createAlova } from 'alova'
import { axiosRequestAdapter } from '@alova/adapter-axios'
import reactHook from 'alova/react'
import { createApis, withConfigType } from './createApis'
import { AxiosError } from 'axios'
import { userStore } from '../stores'

export const alovaInstance = createAlova({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  // baseURL: '',
  statesHook: reactHook,
  cacheFor: {
    GET: null,
  },
  requestAdapter: axiosRequestAdapter(),
  beforeRequest: (method) => {
    const tk = userStore.tk
    if (!method.meta?.ignoreToken) {
      method.config.headers.tk = tk ?? 'tk'
    }
    if (!method.meta?.generateId) {
      const generateId = generateUUID()
      method.meta = { ...(method.meta ?? {}), generateId }
    }
    if (method.meta?.isUpload) {
      method.config.headers['Content-Type'] = 'multipart/form-data'
    }
  },
  responded: {
    onSuccess: async (response, method) => {
      console.log('response', response)
      const { status, headers } = response
      if (200 === status) {
        // http请求通过
        const { data, code, msg } = response.data
        // 先判断是否是下载文件，如果是则直接返回response
        if (method.meta?.isDownload) {
          return response
        }
        // 判断code是否为0
        if (0 === code) {
          // 判断是否需要headers返回的数据
          if (method.meta?.needHeaders) {
            return {
              data,
              headers,
            }
          }

          // MARK: 测试接口报错可以在这里进行编辑
          // if (method.url.includes('/apply/page')) {
          //   return Promise.reject({
          //     code: 11111,
          //     msg: '测试一下列表报错',
          //   })
          // }

          return data
        } else {
          // 抛出错误
          return Promise.reject({
            code,
            msg,
          })
        }
      }
    },
    onError: (error: AxiosError) => {
      console.error('error', error)
    },
  },
})

export const $$userConfigMap = withConfigType({
  'auth.LoginGetCodeImg': {
    meta: {
      needHeaders: true,
    },
    transform: (data: unknown) => {
      const nd = data as { data: string; headers: Record<string, string> }
      const prefix = 'data:image/png;base64,'
      return {
        headers: nd.headers,
        data: prefix + nd.data,
      }
    },
  },
  'auth.LoginUnitePassword': {
    // transform: (data: Result) => {
    //   return data.data as LoginVoOutUserVO
    // },
  },
})

const Apis = createApis(alovaInstance, $$userConfigMap)

export default Apis

function generateUUID(): string {
  // Generate a random UUID
  const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
    /[xy]/g,
    function (c) {
      const r = (Math.random() * 16) | 0,
        v = c === 'x' ? r : (r & 0x3) | 0x8
      return v.toString(16)
    }
  )

  return uuid
}
